package com.inspector.app.ui.widget

import android.text.InputFilter
import android.text.Spanned
import com.inspector.app.util.ToastUtil


/**
 * 指定输入范围
 * https://stackoverflow.com/questions/14212518/is-there-a-way-to-define-a-min-and-max-value-for-edittext-in-android
 */
class InputFilterMinMax : InputFilter {
    private var min: Int = 0
    private var max: Int = 0
    private var tips: String? = null

    constructor(min: Int, max: Int) {
        this.min = min
        this.max = max
    }

    constructor(min: Int, max: Int, tips: String) {
        this.min = min
        this.max = max
        this.tips = tips
    }

    override fun filter(
        source: CharSequence,
        start: Int,
        end: Int,
        dest: Spanned,
        dstart: Int,
        dend: Int
    ): CharSequence? {
        try {
            val input = Integer.parseInt(dest.toString() + source.toString())
            if (isInRange(min, max, input))
                return null
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if (!tips.isNullOrEmpty()) {
            ToastUtil.getInstance().showToast(tips)
        }
        return ""
    }

    private fun isInRange(a: Int, b: Int, c: Int): Boolean {
        return if (b > a) c in a..b else c in b..a
    }
}